import React, { useState } from "react";
import PropTypes from "prop-types";
import Wrap from "../../hoc/Wrap";

const Select = ({
  value: inValue,
  defaultValue,
  size,
  cls,
  title,
  options,
  placeholder,
  disabled,
  listHeight,
  showSearch,

  onBlur,
  onSelect,
  onChange,

  INPUT_PADDING,
  ...rest
}) => {
  const [visible, setVisible] = useState(false)
  const optionLab = getOption(inValue ?? defaultValue, options).label
  const goalLab = optionLab ? optionLab : inValue ?? defaultValue
  const [value, setValue] = useState(goalLab)
  React.useEffect(() => { defaultValue === undefined && setValue(goalLab) }, [defaultValue, goalLab])
  console.log('value', value);

  const [lastVal, setLastVal] = useState()
  const handleInputChange = (e) => {
    setValue(e.target.value)
  }
  const handleFocus = (e) => {
    if (disabled) return e.stopPropagation()
    setVisible(true)
  }
  const handleBlur = () => {
    setTimeout(() => {
      setVisible(false)
      getOption(value, options).notMatch && !getOption(lastVal, options).notMatch && setValue(lastVal)
    }, 200)
    onBlur && onBlur()
  };
  const handleClickOption = (val) => {
    setValue(val)
    if (!getOption(val, options).notMatch) {
      setLastVal(val)
    }
    onSelect && onSelect(val)
    onChange && val !== value && onChange(getOption(val, options).value)
  }

  options = options.map(option => ({ value: option.value, label: option.label || option.value }))

  const containerRef = React.useRef(null)
  const [containerWidth, setContainerWidth] = React.useState(null);

  const textRef = React.useRef(null)
  const [textWidth, setTextWidth] = React.useState(null)

  const [, forceUpdate] = React.useState({});
  function onPopupMouseEnter() {
    forceUpdate({});
  }

  React.useLayoutEffect(() => {
    const newWidth = Math.ceil(containerRef.current.offsetWidth);
    if (containerWidth !== newWidth) {
      setContainerWidth(newWidth);
    }

    const newTextWidth = Math.ceil(textRef.current.offsetWidth);
    if (textWidth != newTextWidth) {
      setTextWidth(newTextWidth)
    }
  }, [containerWidth, textWidth]);


  const inputCls = {
    'text-xs': size === 'small',
    'text-lg': size === 'large',
    'bg-gray-300 cursor-not-allowed': disabled,
    'w-full': rest?.style?.width
  }
  const inputStyle = {
    'small': { height: '22px', paddingLeft: INPUT_PADDING, paddingRight: 2 * INPUT_PADDING, width: rest?.style?.width ? undefined : textWidth + 3 * INPUT_PADDING },
    'default': { height: '30px', paddingLeft: INPUT_PADDING, paddingRight: 2 * INPUT_PADDING, width: rest?.style?.width ? undefined : textWidth + 3 * INPUT_PADDING },
    'large': { height: '38px', paddingLeft: INPUT_PADDING, paddingRight: 2 * INPUT_PADDING, width: rest?.style?.width ? undefined : textWidth + 3 * INPUT_PADDING },
  }[size]

  const textStyle = {
    'small': { lineHeight: '22px' },
    'default': { lineHeight: '30px' },
    'large': { lineHeight: '38px' },
  }[size]
  const popUpStyle = {
    width: containerWidth
  }

  return (
    <div className="inline-block relative" onFocusCapture={handleFocus} onBlur={handleBlur} {...rest}>
      <div className='flex relative w-full'>
        {/* <span className='w-full absolute'> */}
        <input className={cls(inputCls)} style={inputStyle} type="text" value={value} placeholder={placeholder} autoComplete="off" disabled={disabled} onChange={handleInputChange} onClickCapture={(e) => console.log(222)} ref={containerRef} />
        {/* </span> */}
        <span className='absolute -z-10' style={textStyle} ref={textRef}>{value}</span>
        <span className="absolute inset-y-0 flex items-center pointer-events-none" style={{ left: containerWidth - INPUT_PADDING * 2 }}>
          <svg className="h-5 w-5 text-gray-400" viewBox="0 0 20 20" fill="none" stroke="currentColor">
            <path d="M7 7l3-3 3 3m0 6l-3 3-3-3" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"></path>
          </svg>
        </span>
      </div>
      <div className={`absolute mt-1 bg-white shadow-lg rounded-md ${visible ? 'block' : 'hidden'}`} style={popUpStyle} >
        <ul className="max-h-56 text-base overflow-auto leading-6 rounded-md shadow-xs">
          {options && options.map(option => {
            return (
              <li className="ly-select-item" onClick={() => handleClickOption(option.label)} value={option.value} key={option.value}>{option.label}</li>
            )
          })}
        </ul>
      </div>
    </div>
  )
}


const getOption = (val, options) => {
  for (let index = 0; index < options.length; index++) {
    const option = options[index];
    if (val === option.label) {
      return { isLabelMatch: true, ...option }
    } else if (val === option.value) {
      return { isValueMatch: true, ...option }
    }
  }
  return { notMatch: true }
}

Select.propTypes = {
  value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  placeholder: PropTypes.string,
  size: PropTypes.string,
}

Select.defaultProps = {
  size: 'default',
  disabled: false,
  INPUT_PADDING: 12
}

export default Wrap(
  'ly-select'
)(Select);
